import { Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import http from '../../../api'
import { CircleUser } from '../../../myTypes'
import { AttentionParams } from '../../../pages/CircleDetail'
import Loading from '../Loading'
import style from './index.module.css'

export default function DetailTopNav(props: { circleUser: CircleUser | undefined; attentionParams: AttentionParams | undefined }) {
  const navigate = useNavigate()
  const { circleUser, attentionParams } = props
  const [count, setCount] = useState(1)
  const [attention, setAttention] = useState(false)
  useEffect(() => {
    if (attentionParams && count === 1) {
      attentionDel()
    }
  }, [attentionParams])

  async function attentionDel() {
    const data = await http('delete', '/mty/circleAttention/del', attentionParams)
    Toast.clear()
    if (data && data.code === 200) {
      if (count === 1) {
        attentionAdd()
        setCount(10)
      } else {
        setAttention(false)
      }
    }
  }
  async function attentionAdd() {
    const data = await http('get', '/mty/circleAttention/add', attentionParams)
    Toast.clear()
    if (data && data.code === 200) {
      setAttention(true)
    }
  }
  function toggleAttention() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    if (attention) {
      attentionDel()
    } else {
      attentionAdd()
    }
  }

  return (
    <div className={style['top-nav']}>
      <div className={style['back-icon']} onClick={() => navigate(-1)}>
        <img src="/static/arrow/icon-down-closed-9e9.png" alt="" />
      </div>
      {/* 用户头像和名字 */}
      <div className={style['author-container']}>
        <div className={style['head']}>
          <img src={circleUser?.head} alt="" />
        </div>
        <div className={style['author-nickname']}>{circleUser?.name}</div>
        <div className={style.attention} onClick={toggleAttention}>
          {attention ? <div className={style['is-attention']}>已关注</div> : <div className={style['no-attention']}>关注</div>}
        </div>
      </div>
      {/* 右侧图标按钮 */}
      <div className={style['right-icon']}>
        <img src="/static/use/icon-btn-more-9e9.png" alt="" />
      </div>
    </div>
  )
}
